package services

import (
	"context"
	"database/sql"
	db "dhuviewer/db_query"

	"github.com/google/uuid"
)

func AddSubWithCommit(uid uuid.UUID, extraUsr uuid.UUID) error {
	tx, err := pq.BeginTx(context.Background(), &sql.TxOptions{Isolation: sql.LevelReadCommitted})
	if err != nil {
		tx.Rollback()
		return err
	}
	withTxQuery := db.New(pq).WithTx(tx)
	err = withTxQuery.AddSubList(context.Background(), db.AddSubListParams{
		Uid:         uid,
		ArrayAppend: extraUsr,
	})
	if err != nil {
		tx.Rollback()
		return err
	}
	err = withTxQuery.UpdateSocailHonorInc(context.Background(), extraUsr)
	if err != nil {
		tx.Rollback()
		return err
	}
	tx.Commit()
	return nil
}

func DelSubWithCommit(uid uuid.UUID, extraUsr uuid.UUID) error {
	tx, err := pq.BeginTx(context.Background(), &sql.TxOptions{Isolation: sql.LevelReadCommitted})
	if err != nil {
		tx.Rollback()
		return err
	}
	withTxQuery := db.New(pq).WithTx(tx)
	err = withTxQuery.DeleteSubOne(context.Background(), db.DeleteSubOneParams{
		Uid:         uid,
		ArrayRemove: extraUsr,
	})
	if err != nil {
		tx.Rollback()
		return err
	}
	err = withTxQuery.UpdateSocailHonorDec(context.Background(), extraUsr)
	if err != nil {
		tx.Rollback()
		return err
	}
	tx.Commit()
	return nil
}
